package com.ambitor.ipro.app.gen;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.DataMap;
import com.ambitor.grass.util.data.DatasetList;
import com.ambitor.grass.util.data.IData;
import com.ambitor.grass.util.data.IDataset;
import com.ambitor.ipro.entities.TradeState;
import com.ambitor.ipro.entities.TradeType;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.LocalConnectionUtils;
import com.ambitor.ipro.util.SkyenccUtil;

public class TaskGenerator extends TimerTask {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private SuperDao superDao = null;
	private Connection conn = null;

	public TaskGenerator() {
	}

	@Override
	public void run() {
		try {
			conn = getConnection();
			superDao = new SuperDaoImpl(conn);
			while (true) {
				IDataset userProBatchList = scannUserProBatch();
				if (userProBatchList.size() == 0) {
					return;
				}
				generateTask(userProBatchList);
			}
		} catch (Exception e) {
			logger.error("生成任务过程中发生异常", e);
		} finally {
			try {
				conn.close();
			} catch (SQLException e) {
				logger.warn("conn.close()出现异常", e);
			}
		}
	}

	/**
	 * 扫描tf_p_user_pro_batch
	 * 
	 * @return
	 * @throws Exception
	 */
	private IDataset scannUserProBatch() throws Exception {
		IDataset userProBatchList = superDao.executeBaseOnSqlSql(
				"TF_P_USER_PRO_BATCH", "SELECT_SETTING_TO_GENERATE_TASK");
		return userProBatchList;
	}

	@SuppressWarnings("unchecked")
	private void generateTask(IDataset userProBatchList) throws Exception {
		IDataset updateUserProBatchList = new DatasetList();
		IDataset tradeProBatchList = new DatasetList();
		for (int i = 0; i < userProBatchList.size(); i++) {
			IData userProBatch = userProBatchList.getData(i);
			int frequency = userProBatch.getInt("FREQUENCY");
			String nextExecTime = SkyenccUtil.getNextInstallDate(new Date(),
					frequency);
			IData updateUserProBatch = new DataMap();
			updateUserProBatch.put("NEXT_EXEC_TIME", nextExecTime);
			updateUserProBatch.put("PRO_ID", userProBatch.getString("PRO_ID"));
			updateUserProBatchList.add(updateUserProBatch);

			IData tradeProBatch = buildTrdeProBatch(userProBatch);
			tradeProBatchList.add(tradeProBatch);
		}
		try {
			superDao.update("TF_P_USER_PRO_BATCH", updateUserProBatchList);
			TaskGeneratorHelper.addTask(superDao, tradeProBatchList);
		} catch (Exception e) {
			logger.warn("生成任务的过程中出现异常", e);
		}
	}

	@SuppressWarnings("unchecked")
	private IData buildTrdeProBatch(IData userProBatch) throws Exception {
		IData tradeProBatch = new DataMap();
		tradeProBatch.put("USER_ID", userProBatch.getString("USER_ID"));
		tradeProBatch.put("NICK", userProBatch.getString("NICK"));
		tradeProBatch.put("TRADE_STATE", TradeState.UN_EXECUTE);// 未执行
		tradeProBatch.put("TRADE_TYPE", TradeType.SCANN_INSTALL);// 扫描安装
		tradeProBatch.put("PRO_ID", userProBatch.getString("PRO_ID"));
		tradeProBatch.put("PRIORITY", Constants.LOW_PRIORITY);
		tradeProBatch.put("CREATE_TIME", SkyenccUtil.formatDate(new Date()));
		String planExecTime = SkyenccUtil.getPlanExecTime(new Date());
		tradeProBatch.put("PLAN_EXEC_TIME", planExecTime);
		tradeProBatch.put("REMARK", "扫描安装");
		return tradeProBatch;
	}

	private Connection getConnection() {
		Connection conn = null;
		int tryTimes = 0;
		while (tryTimes < Constants.TAOBAO_API_CALL_MAX_TIMES) {
			try {
				conn = LocalConnectionUtils.getConnection();
				break;
			} catch (SQLException e) {
				logger.error("获取Connection出现异常");
				tryTimes++;
				sleep(1000);
			}
		}
		return conn;
	}

	private void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException exp) {
		}
	}
}
